﻿using System.Diagnostics;

namespace DimensionsHelper.LanguageService.Symbols;

public class MetadataArealSymbolTable(ISymbol domainSymbol) : SymbolTable
{
    public override ISymbol? DomainSymbol { get; } = domainSymbol;

    protected override Dictionary<string, ISymbol> Symbols { get; } = new(StringComparer.OrdinalIgnoreCase);


    private static string MakeKey(string name, string context, string language, string labelType)
    {
        return $"[Context:{context},Language:{language},Name:{name},LabelType:{labelType}]";
    }


    private static string KeySelector(ISymbol symbol)
    {
        if (symbol is MetadataArealSymbol arealSymbol)
        {
            return MakeKey(arealSymbol.Name, arealSymbol.Context,
                arealSymbol.Language, arealSymbol.LabelType);
        }

        return symbol.Name;
    }


    protected override bool DeclareSymbolCore(ISymbol symbol)
    {
        string key = KeySelector(symbol);
        Debug.Assert(!string.IsNullOrWhiteSpace(key) && symbol.IsMetadata);
        if (Symbols.TryGetValue(key, out ISymbol? definition))
        {
            return definition.Redeclare(symbol);
        }

        Symbols.Add(key, symbol);
        return true;
    }


    /// <summary>
    ///     查找指定命名、上下文类型、语言名下的符号。
    /// </summary>
    /// <param name="name">符号名</param>
    /// <param name="context">上下文类型名</param>
    /// <param name="language">语言名</param>
    /// <param name="labelType">标签类型</param>
    /// <returns>已有符号，如果不存在，返回<see langword="null" /></returns>
    public ISymbol? LookupSymbol(string name, string context, string language, string labelType)
    {
        return Symbols.GetValueOrDefault(MakeKey(name, context, language, labelType));
    }
}